import json
from audioBot.cmd_executors.llm_serve import llm
from framework.frontend.command import Commander
from framework.frontend.speech_client import fallback_tts
from tool.config.config import get_config
import json
import sounddevice as sd
import soundfile as sf

def say_sth(text):
    fallback_tts(text,"./tmp.wav")
    data, samplerate = sf.read("./tmp.wav", dtype='float32')  # 读取音频数据
    sd.play(data, samplerate)  # 播放
    sd.wait()  # 等待播放结束

def chat_executor(recorder):
    # tts_player = TTSPlayer()
    commander = Commander()
    while True:
        recorder.start_recording()
        query = recorder.query_text
        print(f"question: {query}")
        if commander.match_cmd(recorder.query_text,get_config("sys.toml")["AUDIO"]["SLEEP_WORDS"]):
            print("Sleep word detected! Stopping recording.")
            say_sth("再见")
            break
        llm.acceptQuery(query, get_config("config.toml")["LLM"]["API_PORT"], model=get_config("config.toml")["LLM"]["MODEL_NAME"])
        
        buffer = ""
        for response in llm.stream():
            content = json.loads(response)["message"]["content"]
            print(content, end="",flush=True)
            buffer += content
        say_sth(buffer)